<!-- 库存列表 -->
<template>
    <n-layout>
        <n-layout-header>
            <div class="stock_query--info">
                <n-input style="width:180px" :placeholder="$t('placeholder.accompanyName')" v-model:value="queryList.name" clearable></n-input>
                <n-select style="width:180px" v-model:value="queryList.status" :options="[
                    { label: '全部', value: '' },
                    { label: '可点单', value: '0' },
                    { label: '陪玩中', value: '1' },
                ]" :placeholder="$t('placeholder.accomStatus')" clearable>
                </n-select>
                <n-select style="width:180px" v-model:value="queryList.type" :options="businessDict" :placeholder="$t('placeholder.businessType')"
                    clearable>
                </n-select>
            </div>
            <div class="stock_query--info">
                <n-button @click="refreshList" type="info" :loading="loading">{{ $t("button.query") }}</n-button>
                <n-button @click="handleOperation('add', {});" type="primary" :disabled="loading">{{ $t("button.newAccom") }}</n-button>
            </div>
        </n-layout-header>
        <n-layout-content content-style="height:calc(100vh - 135px);padding:0 20px;">
            <n-table :single-line="false">
                <thead class="stock_table--header">
                    <tr>
                        <th align="center" width="13%">{{ $t("tableColumnLabel.accompanyName") }}</th>
                        <th align="center" width="12%">{{ $t("tableColumnLabel.gameRank") }}</th>
                        <th align="center" width="22%">{{ $t("tableColumnLabel.introcution") }}</th>
                        <th align="center" width="15%">{{ $t("tableColumnLabel.price") }}</th>
                        <th align="center" width="10%">{{ $t("tableColumnLabel.sex") }}</th>
                        <th align="center" width="11%">{{ $t("tableColumnLabel.accompanyStatus") }}</th>
                        <th align="center" width="15%">{{ $t("tableColumnLabel.operation") }}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-if="loading">
                        <td colspan="8" align="center">
                            <n-spin size="small" style="margin: 10px 0;"></n-spin>
                        </td>
                    </tr>
                    <template v-else>
                        <tr v-if="stockList.length === 0">
                            <td colspan="8" align="center">{{ $t("text.noDate") }}</td>
                        </tr>
                        <tr v-else v-for="(item, index) in stockList" :key="index">
                            <td align="center">
                                {{ item.name }}
                            </td>
                            <td align="center">
                                {{ item.rank }}
                            </td>
                            <td align="center">
                                <p class="price">{{ item.introduction }}</p>
                            </td>
                            <td align="center">
                                <p class="price">{{ item.price }}{{ $t("unit.moneyEveryHour") }}</p>
                                <P class="vip-count">({{ $t("text.vipPrice") }}：{{ item.discount }})</P>
                            </td>
                            <td align="center">
                                <span>{{ item.sex === '0' ? $t("unit.woman") : $t("unit.man") }}</span>
                            </td>
                            <td align="center">
                                <n-tag size="small" :type="item.status === '0' ? 'success' : 'error'">
                                    {{ item.status === '0' ? $t("status.accomWait") : $t("status.accomProcess") }}
                                </n-tag>
                            </td>
                            <td align="center">
                                <div class="btn__list--grid">
                                    <n-button size="small" type="primary"
                                        @click="handleOperation('edit', item)">{{ $t("button.edit") }}</n-button>
                                    <n-button size="small" type="error"
                                        @click="handleOperation('delete', item)">{{ $t("button.delete") }}</n-button>
                                    <n-button v-if="item.status === '0'" type="info" size="small"
                                        @click="handleOperation('open', item)">
                                        {{ $t("button.takeOrder") }}
                                    </n-button>
                                    <n-button size="small" type="info"
                                        @click="handleOperation('view', item)">{{ $t("button.view") }}</n-button>
                                </div>

                            </td>
                        </tr>
                    </template>
                </tbody>
            </n-table>
        </n-layout-content>
        <n-layout-footer>
            <n-pagination v-model:page="queryList.page" v-model:page-size="queryList.limit"
                :item-count="queryList.total" show-size-picker :page-sizes="[10, 20, 30, 40]"
                @update:page="handlePageChange($event, 'page')"
                @update:page-size="handlePageChange($event, 'limit')" />
        </n-layout-footer>
    </n-layout>
</template>

<script setup lang='ts' name="accomUserComp">
import { getByTag } from '@/api/backend/admin';
import { initStock, updateStockStatus, deleteStock } from '@/api/backend/stock';
import { addOrder } from '@/api/backend/order';
import { useDialog, useMessage } from 'naive-ui';
import { showDialog } from '@/utils/message';
import RegisterHip from './RegisterHip.vue';
import i18n from '@/locales';
import EventEmiiter from '@/utils/EventEmiiter';
const { t } = i18n.global

const message = useMessage();
const emit = defineEmits<{
    (event: 'toDetail', type: 'edit' | 'add' | 'view', row: Partial<AcompUser>): void
}>();
const loading = ref(false);
const dialog = useDialog();
const queryList = reactive({
    page: 1,
    limit: 10,
    total: 0,
    name: '',
    status: '',
    type: ''
});
const isInit = ref(false);
const businessDict = reactive<{
    label: string;
    value: string;
}[]>([]);
const rankDict = reactive<{
    label: string;
    value: string;
}[]>([]);
const stockList = reactive<AcompUser[]>([]);
const refreshList = async () => {
    try {
        loading.value = true;
        if (!isInit.value) {
            // 初始化字典
            const [res1, res2] = await Promise.all([getByTag('historyRank'), getByTag('businessType')]);
            isInit.value = true;
            businessDict.length = 0; // 清空数组
            rankDict.length = 0; // 清空数组
            res1.data.forEach((item: Dict) => {
                rankDict.push({
                    label: item.label,
                    value: item.value
                });
            });
            businessDict.push({
                label: '全部',
                value: ''
            })
            res2.data.forEach((item: Dict) => {
                businessDict.push({
                    label: item.label,
                    value: item.value
                });
            });
        }
        const { data, total } = await initStock(queryList);
        stockList.length = 0;
        queryList.total = total as number;
        (data ?? []).forEach((item: AcompUser) => {
            stockList.push({
                ...item,
                rank: rankDict.find(el => el.value === item.rank)?.label ?? ''
            });
        });
    } catch (error) {
        message.error(`获取库存列表失败: ${error}`);
    } finally {
        loading.value = false;
    }
};
refreshList();
const handleOperation = (type: 'add' | 'edit' | 'delete' | 'view' | 'open', row: Partial<AcompUser>) => {
    if (type === 'add') {
        emit('toDetail', type, {});
    } else if (type === 'edit') {
        emit('toDetail', type, row);
    } else if (type === 'delete') {
        handleDelete(row.id as string);
    } else if (type === 'view') {
        emit('toDetail', type, row);
    } else if (type === 'open') {
        showDialog(
            {
                tilteName: t('form.registerOrder'),
                accomUser: row,
                businessDict,
            },
            {
                title: t('form.registerOrder'),
                onNegativeClick: () => {
                    console.log('取消点击了');
                },
                onPositiveClick: async (closeDialog: Function, componentInstance: any) => {
                    try {
                        EventEmiiter.emit('VIEW:CHANGE_LOADING',true);
                        const { code, accomUserForm, form } = await componentInstance.submitForm?.();
                        if (code !== 200) throw new Error('请完整填写表单！');
                        await Promise.all([updateStockStatus(accomUserForm.id, '1'), addOrder(accomUserForm, form)]);
                        message.success('新增订单成功！');
                        closeDialog();
                        refreshList();
                    } catch (error) {
                        message.error(error instanceof Error ? error.message : '错误！');
                    } finally{
                        EventEmiiter.emit('VIEW:CHANGE_LOADING',false);
                    }
                },
                buttonCancelText:t('text.cancel'),
                buttonConfirmText:t('text.confirm'),
                modalStyle: {
                    width: '80%'
                }
            },
            RegisterHip
        )
    }
}
const handleDelete = async (id: string) => {
    dialog.warning({
        title: '警告',
        content: '你确定？',
        positiveText: '确定',
        negativeText: '不确定',
        draggable: true,
        onPositiveClick: async () => {
            try {
                const response = await deleteStock(id);
                if (response.code !== 200) throw new Error(response.message);
                message.success('删除成功');
            } catch (error) {
                message.error(`删除失败: ${error}`);
            } finally {
                refreshList();
            }
        },
        onNegativeClick: () => {
            message.error('取消')
        }
    })
};
const handlePageChange = (value: number, prop: 'page' | 'limit') => {
    Object.assign(queryList,{
        [prop]:value
    })
    refreshList();
}
</script>
<style scoped lang='scss'>
.n-layout-header {
    height: 60px;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .stock_query--info {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 1rem;
    }
}

.n-layout-footer {
    height: 50px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 20px;
    background: rgba(255, 255, 255, 0.2);
    /* 半透明背景 */
    backdrop-filter: blur(10px);
    /* 背景模糊 */
    -webkit-backdrop-filter: blur(10px);
    /* 兼容性前缀 */
    border-top: 1px solid #E7E7E7;
    /* 可选边框 */
}

.stock_table--header th {
    background: rgb(233, 240, 247);
}

table tr td {
    background: none;
}

table tr:hover {
    background: rgb(250, 252, 255) !important;
    cursor: pointer;
}

.vip-count {
    color: #f40;
    font-size: 0.8em;
    font-weight: 600;
}

.price {
    color: #444;
    font-size: 0.8em;
    font-weight: 600;
    line-height: 0;
    line-height: 0.5em;
}

.btn__list--grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 4px;
}

.no-rent {
    color: #666;
}
</style>